<?php 

namespace pmvc\ioc;

use pmvc\Properties;
use Exception;

class PropertiesDescriptorPostProcessor
	implements DescriptorPostProcessor,
	InitializingObject {

	private $addEnvironmentVariables 		= FALSE;
	private $environmentVariablesOverride	= FALSE;
	private $dieOnError						= TRUE;
	private $propertyFiles					= Array();
	private $properties						= NULL;

	/**
	 * {@inheritDoc}
	 */
	function initialize(ObjectFactory $objectFactory) {
		$this->properties = new Properties();
		if (!$this->environmentVariablesOverride && $this->addEnvironmentVariables) {
			$this->addEnvironmentVariables($this->properties);
		}
		foreach ($this->propertyFiles as $propertyFile) {
			if (file_exists($propertyFile)) {
				$this->properties->loadFromFile($propertyFile);
			} else if ($this->dieOnError) {
				throw new Exception("Error loading properties file: ".$propertyFile);
			}
		}
		if ($this->environmentVariablesOverride && $this->addEnvironmentVariables) {
			$this->addEnvironmentVariables($this->properties);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	function process(ObjectDescriptor $descriptor) {
		$descriptor->class 		= $this->properties->evalPropertyString($descriptor->class);
		$descriptor->singleton 	= $this->properties->evalPropertyString($descriptor->singleton);
		$descriptor->parent 	= $this->properties->evalPropertyString($descriptor->parent);
		$descriptor->lazy 		= $this->properties->evalPropertyString($descriptor->lazy);
		foreach ($descriptor->properties as $prop) {
			$this->processProperty($prop);
		}
	}

	function processProperty(PropertyDescriptor $propDesc) {
		if (is_array($propDesc->value)) {
			foreach ($propDesc->value as $val) {
				$this->processProperty($val);
			}
		} else {
			$propDesc->name = $this->properties->evalPropertyString($propDesc->name);
			$propDesc->value = $this->properties->evalPropertyString($propDesc->value);
		}
	}
	
	private function addEnvironmentVariables(Properties $properties) {
		if (isset($_ENV)) {
			$this->setValue("env", $_ENV);
		}
		if (isset($_SERVER)) {
			$this->setValue("server", $_SERVER);
		}
		if (isset($argv)) {
			$this->setValue("argv", $argv);
		}
		$this->setValue("ini", ini_get_all());
	}

	private function setValue($baseName, $value) {
		if (!is_array($value)) {
			$this->properties->setProperty($baseName, $value);
		} else {
			foreach ($value as $key => $val) {
				$this->setValue($baseName.".".$key, $val);
			}
		}
	}

	public function setAddEnvironmentVariables($addEnvironmentVariables) {
		$this->addEnvironmentVariables = $addEnvironmentVariables;
	}

	public function setEnvironmentVariablesOverride($environmentVariablesOverride) {
		$this->environmentVariablesOverride = $environmentVariablesOverride;
	}

	public function setPropertyFiles($propertyFiles) {
		$this->propertyFiles = $propertyFiles;
	}

	public function setDieOnError($dieOnError) {
		$this->dieOnError = $dieOnError;
	}

}



?>